﻿package com.rbac.system.service.impl;

import com.rbac.system.entity.Menu;
import com.rbac.system.entity.Role;
import com.rbac.system.entity.RoleMenu;
import com.rbac.system.entity.UserRole;
import com.rbac.system.mapper.MenuMapper;
import com.rbac.system.mapper.RoleMapper;
import com.rbac.system.mapper.RoleMenuMapper;
import com.rbac.system.mapper.UserRoleMapper;
import com.rbac.system.service.MenuService;
import com.rbac.system.vo.MenuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    
    @Autowired
    private MenuMapper menuMapper;
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    
    @Override
    public List<MenuVO> getUserMenus(Long userId) {
        System.out.println("=== MenuService调试开始 ===");
        System.out.println("查询用户ID: " + userId + " 的菜单权限");
        
        // 获取用户角色
        List<UserRole> userRoles = userRoleMapper.selectByUserId(userId);
        System.out.println("1. 用户角色查询结果:");
        System.out.println("   角色数量: " + (userRoles != null ? userRoles.size() : 0));
        if (userRoles != null) {
            for (UserRole ur : userRoles) {
                System.out.println("   角色记录: id=" + ur.getId() + ", userId=" + ur.getUserId() + ", roleId=" + ur.getRoleId() + ", deleted=" + ur.getDeleted());
            }
        }
        
        if (userRoles.isEmpty()) {
            System.out.println("用户没有分配角色，返回空菜单");
            return new ArrayList<>();
        }
        
        List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        System.out.println("2. 提取的角色ID列表: " + roleIds);
        
        // 所有用户都根据权限显示菜单，不再给管理员特殊待遇
        List<RoleMenu> roleMenus = roleMenuMapper.selectByRoleIds(roleIds);
        System.out.println("3. 角色菜单权限查询结果:");
        System.out.println("   权限记录数量: " + (roleMenus != null ? roleMenus.size() : 0));
        if (roleMenus != null && !roleMenus.isEmpty()) {
            System.out.println("   前10条权限记录:");
            for (int i = 0; i < Math.min(10, roleMenus.size()); i++) {
                RoleMenu rm = roleMenus.get(i);
                System.out.println("   记录" + (i+1) + ": id=" + rm.getId() + ", roleId=" + rm.getRoleId() + ", menuId=" + rm.getMenuId() + ", deleted=" + rm.getDeleted());
            }
            if (roleMenus.size() > 10) {
                System.out.println("   ... 还有 " + (roleMenus.size() - 10) + " 条记录");
            }
        }
        
        if (roleMenus.isEmpty()) {
            System.out.println("角色没有分配菜单权限，返回空菜单");
            return new ArrayList<>();
        }
        
        List<Long> menuIds = roleMenus.stream()
                .map(RoleMenu::getMenuId)
                .distinct()
                .collect(Collectors.toList());
        System.out.println("4. 提取的菜单ID列表:");
        System.out.println("   菜单ID数量: " + menuIds.size());
        System.out.println("   菜单ID列表: " + menuIds);
        
        // 获取菜单信息（只获取菜单类型，不包括按钮）
        List<Menu> allMenus = menuMapper.selectByIds(menuIds);
        System.out.println("5. 菜单信息查询结果:");
        System.out.println("   查询到的菜单数量: " + (allMenus != null ? allMenus.size() : 0));
        if (allMenus != null && !allMenus.isEmpty()) {
            for (Menu menu : allMenus) {
                System.out.println("   菜单: id=" + menu.getId() + ", name=" + menu.getMenuName() + ", type=" + menu.getMenuType() + ", status=" + menu.getStatus() + ", deleted=" + menu.getDeleted());
            }
        }
        
        List<Menu> menus = allMenus.stream()
                .filter(menu -> ("MENU".equals(menu.getMenuType()) || "DIRECTORY".equals(menu.getMenuType())) && menu.getStatus() == 1)
                .collect(Collectors.toList());
        
        System.out.println("6. 过滤后的有效菜单:");
        System.out.println("   有效菜单数量: " + menus.size());
        for (Menu menu : menus) {
            System.out.println("   有效菜单: id=" + menu.getId() + ", name=" + menu.getMenuName() + ", path=" + menu.getPath() + ", parentId=" + menu.getParentId());
        }
        
        // 转换为VO并构建菜单树
        List<MenuVO> allMenuVOs = menus.stream().map(menu -> {
            MenuVO menuVO = new MenuVO();
            BeanUtils.copyProperties(menu, menuVO);
            return menuVO;
        }).collect(Collectors.toList());
        
        // 构建菜单树，从根节点（parentId = 0）开始
        List<MenuVO> result = buildMenuTree(allMenuVOs, 0L);
        
        System.out.println("7. 最终菜单树:");
        System.out.println("   顶级菜单数量: " + result.size());
        for (MenuVO menuVO : result) {
            printMenuTree(menuVO, 0);
        }
        
        System.out.println("=== MenuService调试结束 ===");
        return result;
    }
    
    @Override
    public List<String> getUserButtons(Long userId) {
        // 获取用户角色
        List<UserRole> userRoles = userRoleMapper.selectByUserId(userId);
        
        if (userRoles.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        
        // 所有用户都根据权限获取按钮，不再给管理员特殊待遇
        List<RoleMenu> roleMenus = roleMenuMapper.selectByRoleIds(roleIds);
        
        if (roleMenus.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<Long> menuIds = roleMenus.stream()
                .map(RoleMenu::getMenuId)
                .distinct()
                .collect(Collectors.toList());
        
        // 获取按钮权限
        List<Menu> allMenus = menuMapper.selectByIds(menuIds);
        List<Menu> buttons = allMenus.stream()
                .filter(menu -> "BUTTON".equals(menu.getMenuType()) && menu.getStatus() == 1)
                .collect(Collectors.toList());
        
        return buttons.stream()
                .map(Menu::getMenuCode)
                .collect(Collectors.toList());
    }
    
    private List<MenuVO> buildMenuTree(List<MenuVO> menus, Long parentId) {
        return menus.stream()
                .filter(menu -> {
                    if (parentId == null) {
                        return menu.getParentId() == null || menu.getParentId() == 0;
                    } else {
                        return parentId.equals(menu.getParentId());
                    }
                })
                .map(menu -> {
                    List<MenuVO> children = buildMenuTree(menus, menu.getId());
                    menu.setChildren(children);
                    return menu;
                })
                .collect(Collectors.toList());
    }
    
    // 辅助方法：打印菜单树
    private void printMenuTree(MenuVO menu, int level) {
        String indent = "   " + "  ".repeat(level);
        System.out.println(indent + "菜单: " + menu.getMenuName() + " (id=" + menu.getId() + ", path=" + menu.getPath() + ")");
        if (menu.getChildren() != null && !menu.getChildren().isEmpty()) {
            for (MenuVO child : menu.getChildren()) {
                printMenuTree(child, level + 1);
            }
        }
    }
    
    private void addParentMenus(Long parentId, List<Menu> menus) {
        if (parentId != null && parentId != 0) {
            // 检查是否已经添加过该菜单
            boolean alreadyExists = menus.stream().anyMatch(menu -> menu.getId().equals(parentId));
            if (!alreadyExists) {
                Menu parentMenu = menuMapper.selectById(parentId);
                if (parentMenu != null && parentMenu.getStatus() == 1 && ("MENU".equals(parentMenu.getMenuType()) || "DIRECTORY".equals(parentMenu.getMenuType()))) {
                    menus.add(parentMenu);
                    addParentMenus(parentMenu.getParentId(), menus);
                }
            }
        }
    }
} 

